package com.rh.number.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.rh.number.entity.numberEntity;
import com.rh.number.service.NumberService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Slf4j
public class NumberImportListener implements ReadListener<numberEntity> {

    // 依赖服务
    private final NumberService numberService;

    // 校验规则
    private static final Pattern PHONE_PATTERN = Pattern.compile("^1[3-9]\\d{9}$");
    private static final Pattern PROVINCE_PATTERN = Pattern.compile("^[\\u4e00-\\u9fa5]{2,10}$");
    private static final Set<String> ALLOWED_TYPES = Set.of("手机号码", "固定电话");

    // 数据存储
    private final List<numberEntity> validData = new ArrayList<>(512);  // 有效数据缓存
    private final Map<Long, Integer> numToRowMap = new HashMap<>(512);// 号码->行号映射
    private final List<String> errorMessages = new ArrayList<>();      // 错误信息（带行号）

    // 统计指标
    private int totalRows = 0;
    private int successCount = 0;

    public NumberImportListener(NumberService numberService) {
        this.numberService = numberService;
    }

    @Override
    public void invoke(numberEntity entity, AnalysisContext context) {
        totalRows++;
        int rowNumber = context.readRowHolder().getRowIndex() + 1;

        try {
            // 基础校验
            String errorMsg = validateBasic(entity, rowNumber);
            if (errorMsg != null) {
                errorMessages.add(errorMsg);
                return;
            }

            // 记录号码与行号映射
            numToRowMap.put(entity.getNum(), rowNumber);
            validData.add(entity);

        } catch (Exception e) {
            errorMessages.add(formatError(rowNumber, "数据解析异常: " + e.getMessage()));
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        if (CollectionUtils.isEmpty(validData)) {
            return;
        }

        try {
            // 1. 批量查重
            Set<Long> existingNums = new HashSet<>(numberService.selectByNum(extractNums(validData)));

            // 2. 分割数据：新数据 vs 重复数据
            List<numberEntity> newData = new ArrayList<>(validData.size());
            validData.forEach(entity -> {
                if (existingNums.contains(entity.getNum())) {
                    errorMessages.add(formatError(
                            numToRowMap.get(entity.getNum()),
                            "号码 " + entity.getNum() + " 已存在"
                    ));
                } else {
                    setDefaultValues(entity);
                    newData.add(entity);
                }
            });

            // 3. 批量插入新数据
            if (!newData.isEmpty()) {
                numberService.batchInsert(newData);
                successCount = newData.size();
            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 基础字段校验（非空、格式）
     */
    private String validateBasic(numberEntity entity, int rowNumber) {
        // 号码校验
        if (entity.getNum() == null) {
            return formatError(rowNumber, "号码不能为空");
        }
        if (!PHONE_PATTERN.matcher(String.valueOf(entity.getNum())).matches()) {
            return formatError(rowNumber, "手机号格式错误");
        }

        // 省份校验
        if (StringUtils.isBlank(entity.getProvince())) {
            return formatError(rowNumber, "省份不能为空");
        }
        if (!PROVINCE_PATTERN.matcher(entity.getProvince()).matches()) {
            return formatError(rowNumber, "省份需为2-10个汉字");
        }

        // 类型校验
        if (!ALLOWED_TYPES.contains(entity.getType())) {
            return formatError(rowNumber, "类型必须为[手机号码, 固定电话]");
        }

        return null;
    }

    /**
     * 设置默认值（避免数据库约束问题）
     */
    private void setDefaultValues(numberEntity entity) {
        if (entity.getMonthlyRent() == null) {
            entity.setMonthlyRent(String.valueOf(0.0));
        }
        if (StringUtils.isBlank(entity.getState())) {
            entity.setState("未激活");
        }
    }

    /**
     * 提取号码列表（用于批量查重）
     */
    private List<Long> extractNums(List<numberEntity> entities) {
        return entities.stream()
                .map(numberEntity::getNum)
                .collect(Collectors.toList());
    }

    /**
     * 格式化错误信息
     */
    private String formatError(int rowNumber, String message) {
        return String.format("第%d行: %s", rowNumber, message);
    }

    /**
     * 获取导入结果（Controller调用）
     */
    public Map<String, Object> getImportResult() {
        return new HashMap<String, Object>() {{
            put("total", totalRows);
            put("success", successCount);
            put("errors", errorMessages);
        }};
    }
}